#include "watermark.h"
#include <QFontMetrics>

void Watermark::addWatermark(QImage& image, const QString& text)
{
    QPainter painter(&image);
    addWatermark(painter, image.rect(), text);
}

void Watermark::addWatermark(QPainter& painter, const QRect& rect, const QString& text)
{
    painter.save();
    drawWatermark(painter, rect, text);
    painter.restore();
}

void Watermark::drawWatermark(QPainter& painter, const QRect& rect, const QString& text)
{
    QFont watermarkFont("Arial", FONT_SIZE);
    painter.setFont(watermarkFont);
    painter.setPen(QColor(128, 128, 128, OPACITY));
    
    QFontMetrics fm(watermarkFont);
    QSize textSize = fm.size(Qt::TextSingleLine, text);
    
    // 计算水印间距
    int horizontalSpacing = rect.width() / (HORIZONTAL_COUNT - 1);
    int verticalSpacing = rect.height() / (VERTICAL_COUNT - 1);
    
    // 在整个区域上均匀分布水印
    for (int y = 0; y < VERTICAL_COUNT; ++y) {
        for (int x = 0; x < HORIZONTAL_COUNT; ++x) {
            painter.save();
            
            // 计算水印位置
            int xPos = rect.left() + x * horizontalSpacing;
            int yPos = rect.top() + y * verticalSpacing;
            
            // 移动到水印位置并旋转
            painter.translate(xPos, yPos);
            painter.rotate(-45);
            
            // 绘制水印，考虑文字大小进行偏移
            painter.drawText(-textSize.width()/2, textSize.height()/4, text);
            
            painter.restore();
        }
    }
} 